
#include "SimpleGA.h"

void SimpleGA::step()
{
  int i, mut, c1, c2;
  GAGenome *mom, *dad;   

  for(i=0; i<pop->size()-1; i+=2)
  {	
    mom = &(selectsch->select());  
    dad = &(selectsch->select());

    if(randObj->GAFlipCoin(pcross)) {
     GAGenome *sis = &pop0->individual(i);
     GAGenome *bro = &pop0->individual(i+1);
     mom->cross(*dad, sis, bro);
    }
    else {
      pop0->individual(i) = *mom;
      pop0->individual(i+1) = *dad;
    }

    pop0->individual( i ).mutate(pmut);
    pop0->individual(i+1).mutate(pmut);
  }

  if(pop->size() % 2 != 0)
  {	// do the remaining population member
    mom = &(selectsch->select());  
    dad = &(selectsch->select());

    if(randObj->GAFlipCoin(pcross)){
     GAGenome *sis = &pop0->individual(i);
     mom->cross(*dad, sis, NULL);
    }
    else{
      if(randObj->GAFlipCoin(0.5)) {
        pop0->individual(i) = *mom;
	}
      else {
        pop0->individual(i) = *dad;
	}
    }

    pop0->individual( i ).mutate(pmut);
  }

  pop0->evaluate();	

// carry the best individual from the old
// population into the current population.  
  pop0->sort();
  if(pop->fitmax() > pop0->fitmax()) {
      pop0->individual(pop0->size()-1) = pop->best();	
      pop0->sort();
      pop0->stats();
      }

  // swap population
  GAPopulation* temp = pop;
  pop = pop0;
  pop0 = temp;

  selectsch->update(pop);
}
